import React, { useState, useEffect, useRef } from 'react';
import { 
  Card, 
  Input, 
  Button, 
  List, 
  Avatar, 
  Spin, 
  Alert, 
  Select,
  Space,
  Typography,
  Divider
} from 'antd';
import { 
  SendOutlined, 
  RobotOutlined, 
  UserOutlined,
  DeleteOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import { apiService } from '../services/apiService';
import './Chat.css';

const { TextArea } = Input;
const { Option } = Select;
const { Text } = Typography;

interface ChatMessage {
  id: number;
  user_message: string;
  ai_response: string;
  timestamp: string;
  decision_rule_id?: number;
}

interface DecisionRule {
  id: number;
  name: string;
  description: string;
}

const Chat: React.FC = () => {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [inputValue, setInputValue] = useState('');
  const [loading, setLoading] = useState(false);
  const [sessionId, setSessionId] = useState<string>('');
  const [decisionRules, setDecisionRules] = useState<DecisionRule[]>([]);
  const [selectedRule, setSelectedRule] = useState<number | undefined>();
  const [error, setError] = useState<string | null>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 获取决策规则
  useEffect(() => {
    const fetchDecisionRules = async () => {
      try {
        const response = await apiService.get('/api/ai-decision/rules');
        if (response.success) {
          setDecisionRules(response.rules);
        }
      } catch (err) {
        console.error('Failed to fetch decision rules:', err);
      }
    };

    fetchDecisionRules();
  }, []);

  // 发送消息
  const sendMessage = async () => {
    if (!inputValue.trim()) return;

    const userMessage = inputValue.trim();
    setInputValue('');
    setLoading(true);
    setError(null);

    try {
      const response = await apiService.post('/api/chat/send', {
        message: userMessage,
        session_id: sessionId,
        decision_rule_id: selectedRule
      });

      if (response.session_id) {
        setSessionId(response.session_id);
      }

      // 添加新消息到列表
      const newMessage: ChatMessage = {
        id: Date.now(),
        user_message: userMessage,
        ai_response: response.ai_response,
        timestamp: response.timestamp,
        decision_rule_id: response.decision_rule_id
      };

      setMessages(prev => [...prev, newMessage]);
    } catch (err: any) {
      setError(err.message || '发送消息失败');
      console.error('Send message error:', err);
    } finally {
      setLoading(false);
    }
  };

  // 清空对话
  const clearChat = () => {
    setMessages([]);
    setSessionId('');
    setError(null);
  };

  // 加载历史对话
  const loadChatHistory = async (sessionId: string) => {
    try {
      setLoading(true);
      const response = await apiService.get(`/api/chat/history/${sessionId}`);
      if (response.success) {
        setMessages(response.history);
        setSessionId(sessionId);
      }
    } catch (err) {
      setError('加载历史对话失败');
      console.error('Load chat history error:', err);
    } finally {
      setLoading(false);
    }
  };

  // 处理回车键
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  return (
    <div className="chat-container page-transition">
      <div className="chat-header">
        <h1>🤖 AI智能对话</h1>
        <Space>
          <Select
            placeholder="选择决策规则"
            style={{ width: 200 }}
            allowClear
            value={selectedRule}
            onChange={setSelectedRule}
          >
            {decisionRules.map(rule => (
              <Option key={rule.id} value={rule.id}>
                {rule.name}
              </Option>
            ))}
          </Select>
          <Button 
            icon={<ReloadOutlined />} 
            onClick={clearChat}
            danger
          >
            清空对话
          </Button>
        </Space>
      </div>

      {error && (
        <Alert
          message="错误"
          description={error}
          type="error"
          showIcon
          closable
          style={{ marginBottom: 16 }}
        />
      )}

      <div className="chat-content">
        <Card className="chat-card">
          <div className="messages-container">
            {messages.length === 0 && !loading && (
              <div className="empty-state">
                <RobotOutlined style={{ fontSize: 48, color: '#1890ff' }} />
                <h3>开始与AI对话</h3>
                <p>我可以帮助您分析数据、制定决策、回答问题</p>
                {selectedRule && (
                  <div className="selected-rule">
                    <Text type="secondary">
                      当前使用决策规则: {decisionRules.find(r => r.id === selectedRule)?.name}
                    </Text>
                  </div>
                )}
              </div>
            )}

            <List
              dataSource={messages}
              renderItem={(message) => (
                <List.Item className="message-item">
                  <div className="message-container">
                    {/* 用户消息 */}
                    <div className="message user-message">
                      <Avatar icon={<UserOutlined />} className="user-avatar" />
                      <div className="message-content">
                        <div className="message-text">{message.user_message}</div>
                        <div className="message-time">
                          {new Date(message.timestamp).toLocaleString()}
                        </div>
                      </div>
                    </div>

                    {/* AI回复 */}
                    <div className="message ai-message">
                      <Avatar icon={<RobotOutlined />} className="ai-avatar" />
                      <div className="message-content">
                        <div className="message-text">{message.ai_response}</div>
                        <div className="message-time">
                          {new Date(message.timestamp).toLocaleString()}
                        </div>
                      </div>
                    </div>
                  </div>
                </List.Item>
              )}
            />

            {loading && (
              <div className="loading-message">
                <Spin size="small" />
                <span>AI正在思考中...</span>
              </div>
            )}

            <div ref={messagesEndRef} />
          </div>

          <Divider />

          <div className="input-container">
            <TextArea
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder="输入您的问题或决策需求..."
              autoSize={{ minRows: 2, maxRows: 6 }}
              disabled={loading}
            />
            <Button
              type="primary"
              icon={<SendOutlined />}
              onClick={sendMessage}
              loading={loading}
              disabled={!inputValue.trim()}
              className="send-button"
            >
              发送
            </Button>
          </div>
        </Card>
      </div>
    </div>
  );
};

export default Chat;
